<template>
  <el-drawer
    :visible.sync="drawer"
    :with-header="false"
    size="100%"
    class="word-detail-drawer"
  >
    <div class="word-detail-container">
      <!-- 单词头部信息 -->
      <div class="word-header">
        <el-button
          icon="fa-solid fa-arrow-left"
          class="back-btn"
          @click="handleClose"
        />
        <h2 class="word-title">{{ currentWord.fullSpell || currentWord.wordFullSpell || '单词' }}</h2>
        <el-button
          icon="fa-solid fa-volume-up"
          class="pronounce-btn"
          @click="playWordPronunciation"
          :title="isAmerican ? '播放美式发音' : '播放英式发音'"
        />
        <el-button
          class="pronunciation-switch"
          @click="isAmerican = !isAmerican"
        >
          {{ isAmerican ? 'US' : 'UK' }}
        </el-button>
      </div>

      <!-- 音标与词性 -->
      <div class="word-phonetic">
        <span class="phonetic-text">{{ isAmerican ? currentWord.phoneticAm : currentWord.phoneticBr }}</span>
        <span class="part-of-speech">{{ currentWord.partOfSpeech || '词性' }}</span>
        <span class="word-meaning">{{ currentWord.wordMeaning || '释义' }}</span>
      </div>

      <!-- 常用短语 -->
      <div v-if="currentWord.phrases && currentWord.phrases.length" class="section">
        <div class="section-header">
          <h3 class="section-title">常用短语</h3>
          <el-button
            class="translate-switch-btn"
            @click="togglePhraseMode"
            :type="phraseMode === 'default' ? 'warning' : phraseMode === 'cn-to-en' ? 'primary' : 'success'"
          >
            {{ phraseModeTextMap[phraseMode] }}
          </el-button>
        </div>
        <div class="phrases-list">
          <div
            v-for="(phrase, index) in currentWord.phrases"
            :key="index"
            class="phrase-item"
          >
            <div class="phrase-content">
              <span
                class="phrase-text"
                :class="{ 'hidden-text': phraseMode === 'cn-to-en' }"
              >
                {{ phrase.text }}
              </span>
              <el-button
                icon="fa-solid fa-volume-up"
                class="phrase-pronounce-btn"
                @click="playPhrasePronunciation(phrase.text)"
                size="mini"
                v-if="phraseMode !== 'cn-to-en'"
              />
              <!-- 新增复制按钮 -->
              <el-button
                icon="fa-solid fa-copy"
                class="copy-btn"
                @click="copyContent(phrase.text, phrase.meaning, 'phrase')"
                size="mini"
                :title="getCopyBtnTitle('phrase')"
              />
            </div>
            <span
              class="phrase-meaning"
              :class="{ 'hidden-text': phraseMode === 'en-to-cn' }"
            >
              {{ phrase.meaning }}
            </span>
          </div>
        </div>
      </div>

      <!-- 例句 -->
      <div v-if="currentWord.examples && currentWord.examples.length" class="section">
        <div class="section-header">
          <h3 class="section-title">例句</h3>
          <el-button
            class="translate-switch-btn"
            @click="toggleExampleMode"
            :type="exampleMode === 'default' ? 'warning' : exampleMode === 'cn-to-en' ? 'primary' : 'success'"
          >
            {{ exampleModeTextMap[exampleMode] }}
          </el-button>
        </div>
        <div>
          <div
            v-for="(example, index) in currentWord.examples"
            :key="index"
            class="example-item"
          >
            <div class="example-content">
              <span
                class="example-text"
                :class="{ 'hidden-text': exampleMode === 'cn-to-en' }"
              >
                {{ example.sentence }}
              </span>
              <el-button
                icon="fa-solid fa-volume-up"
                class="example-pronounce-btn"
                @click="playExamplePronunciation(example.sentence)"
                size="mini"
                v-if="exampleMode !== 'cn-to-en'"
              />
              <!-- 新增复制按钮 -->
              <el-button
                icon="fa-solid fa-copy"
                class="copy-btn"
                @click="copyContent(example.sentence, example.translation, 'example')"
                size="mini"
                :title="getCopyBtnTitle('example')"
              />
            </div>
            <span
              class="example-meaning"
              :class="{ 'hidden-text': exampleMode === 'en-to-cn' }"
            >
              {{ example.translation }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import AudioCacheUtil from '@/utils/AudioCacheUtil'

export default {
  name: 'WordDetailDrawer',
  props: {
    word: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      drawer: this.visible,
      isAmerican: true, // 美式/英式发音切换（true为美式，false为英式）
      playbackSpeed: 1.0, // 发音播放速度
      currentWord: this.transformedWord,
      // 短语翻译模式：default(默认显示全部)、cn-to-en(中译英，隐藏中文)、en-to-cn(英译中，隐藏英文)
      phraseMode: 'default',
      // 例句翻译模式：同上
      exampleMode: 'default',
      // 模式文本映射表（按钮显示文字）
      phraseModeTextMap: {
        default: '切换模式',
        'cn-to-en': '中译英',
        'en-to-cn': '英译中'
      },
      exampleModeTextMap: {
        default: '切换模式',
        'cn-to-en': '中译英',
        'en-to-cn': '英译中'
      }
    }
  },
  computed: {
    // 转换后的单词数据（处理extendedInfo字段）
    transformedWord() {
      return this.transformWordFormat(this.word)
    }
  },
  watch: {
    // 监听外部显示状态变化，同步到内部drawer
    visible(val) {
      this.drawer = val
    },
    // 监听单词数据变化，重新处理数据
    word(newVal) {
      this.currentWord = newVal.fullSpell ? this.transformedWord : this.currentWord
    }
  },
  methods: {
    // 新增：获取复制按钮的提示文本
    getCopyBtnTitle(type) {
      const mode = type === 'phrase' ? this.phraseMode : this.exampleMode
      if (mode === 'default') {
        return type === 'phrase' ? '复制短语+释义' : '复制例句+翻译'
      } else if (mode === 'cn-to-en') {
        return type === 'phrase' ? '复制短语' : '复制例句'
      } else {
        return type === 'phrase' ? '复制释义' : '复制翻译'
      }
    },

    // 新增：复制内容到剪贴板
    copyContent(enText, cnText, type) {
      const mode = type === 'phrase' ? this.phraseMode : this.exampleMode
      let copyText = ''

      // 根据当前模式判断复制内容
      if (mode === 'default') {
        copyText = `${enText}\n${cnText}` // 默认模式：英文+中文（换行分隔）
      } else if (mode === 'cn-to-en') {
        copyText = enText // 中译英模式：仅英文
      } else {
        copyText = cnText // 英译中模式：仅中文
      }

      // 执行复制操作
      // navigator.clipboard.writeText(copyText)
      //   .then(() => {
      //     this.$notify({ type: 'success', message: '复制成功！' })
      //   })
      //   .catch(err => {
      //     console.error('复制失败:', err)
      //     this.$notify({ type: 'success', message: '复制成功！' })
      //   })
      if (navigator.clipboard && window.isSecureContext) {
        // HTTPS 环境
        navigator.clipboard.writeText(copyText)
        this.$notify({ type: 'success', message: '复制成功！' })
      } else {
        // HTTP 回退方案
        const textarea = document.createElement('textarea')
        textarea.value = copyText
        textarea.style.position = 'fixed'
        textarea.style.opacity = '0'
        document.body.appendChild(textarea)
        textarea.select()
        document.execCommand('copy')
        document.body.removeChild(textarea)
        this.$notify({ type: 'success', message: '复制成功！' })
      }
    },
    // 关闭抽屉并重置状态
    handleClose() {
      this.drawer = false
      this.$emit('update:visible', false)
      // 重置翻译模式为默认
      this.phraseMode = 'default'
      this.exampleMode = 'default'
    },
    // 播放单词发音
    playWordPronunciation() {
      const wordText = this.currentWord.fullSpell || this.currentWord.wordFullSpell
      AudioCacheUtil.play(wordText, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },
    // 播放短语发音
    playPhrasePronunciation(phraseText) {
      AudioCacheUtil.play(phraseText, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },
    // 播放例句发音
    playExamplePronunciation(sentence) {
      AudioCacheUtil.play(sentence, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },
    // 转换单词数据格式（解析extendedInfo）
    transformWordFormat(originalWord) {
      // 解析extendedInfo字段（JSON字符串转对象）
      if (originalWord && originalWord.extendedInfo) {
        try {
          originalWord = JSON.parse(originalWord.extendedInfo)
        } catch (e) {
          console.error('解析单词信息失败', e)
          return {}
        }
      }
      // 处理空数据
      if (!originalWord || !originalWord.word) return {}

      // 格式化返回需要的字段
      return {
        fullSpell: originalWord.word,
        wordFullSpell: originalWord.word,
        phoneticAm: originalWord.phonetics?.us || '', // 美式音标
        phoneticBr: originalWord.phonetics?.uk || '', // 英式音标
        partOfSpeech: originalWord.partOfSpeech || '', // 词性
        wordMeaning: originalWord.meaningOptions?.correct || '', // 正确释义
        // 格式化短语数据
        phrases: originalWord.phrases?.map(phrase => ({
          text: phrase.p, // 短语英文
          meaning: phrase['zh-mean'] // 短语中文释义
        })) || [],
        // 格式化例句数据
        examples: originalWord.examples?.map(example => ({
          sentence: example.e, // 例句英文
          translation: example['zh-mean'] // 例句中文翻译
        })) || [],
        confusions: originalWord.confusions || [], // 易混淆单词
        meaningOptions: originalWord.meaningOptions || {} // 释义选项
      }
    },
    // 切换短语翻译模式（循环切换：default → cn-to-en → en-to-cn）
    togglePhraseMode() {
      switch (this.phraseMode) {
        case 'default':
          this.phraseMode = 'cn-to-en'
          break
        case 'cn-to-en':
          this.phraseMode = 'en-to-cn'
          break
        case 'en-to-cn':
          this.phraseMode = 'default'
          break
        default:
          this.phraseMode = 'default'
      }
    },
    // 切换例句翻译模式（循环切换：default → cn-to-en → en-to-cn）
    toggleExampleMode() {
      switch (this.exampleMode) {
        case 'default':
          this.exampleMode = 'cn-to-en'
          break
        case 'cn-to-en':
          this.exampleMode = 'en-to-cn'
          break
        case 'en-to-cn':
          this.exampleMode = 'default'
          break
        default:
          this.exampleMode = 'default'
      }
    }
  }
}
</script>

<style scoped>
/* 白天主题核心配色 */
.word-detail-drawer {
  background-color: #ffffff; /* 纯白色背景 */
  color: #333333; /* 深色文字 */
}

.word-detail-container {
  padding: 24px;
  max-height: 100vh;
  overflow-y: auto;
  line-height: 1.7;
}

/* 单词头部样式 */
.word-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eeeeee; /* 浅灰色边框 */
}

.back-btn {
  width: 40px;
  height: 40px;
  padding: 0;
  border-radius: 50%;
  background-color: #f5f5f5 !important;
  color: #666666 !important;
  border: none !important;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background-color: #eeeeee !important;
  transform: scale(1.05);
}

.word-title {
  font-size: 32px;
  font-weight: 700;
  margin: 0;
  flex-grow: 1;
  min-width: 0;
  color: #1a1a1a; /* 更深的单词颜色 */
}

.pronounce-btn {
  background-color: #e6f7ff !important; /* 浅蓝色背景 */
  color: #1890ff !important; /* 蓝色图标 */
  border: 1px solid #91d5ff !important;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: all 0.3s ease;
}

.pronounce-btn:hover {
  background-color: #bae7ff !important;
  transform: scale(1.05);
}

.pronunciation-switch {
  background-color: #f5f5f5 !important;
  color: #333333 !important;
  border: 1px solid #dddddd !important;
  border-radius: 20px;
  padding: 4px 12px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.pronunciation-switch:hover {
  background-color: #eeeeee !important;
}

/* 音标与词性样式 */
.word-phonetic {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 28px;
  align-items: center;
}

.phonetic-text {
  color: #666666; /* 深灰色音标 */
  font-style: italic;
  font-size: 16px;
}

.part-of-speech {
  background-color: #f0f7ff;
  color: #1890ff;
  padding: 4px 10px;
  border-radius: 16px;
  font-size: 14px;
}

.word-meaning {
  color: #333333; /* 深色释义 */
  font-size: 16px;
  max-width: 80%;
}

/* 板块通用样式 - 只保留颜色变化动画，移除浮动 */
.section {
  margin-bottom: 32px;
  padding: 16px;
  background-color: #f9f9f9; /* 浅灰色板块背景 */
  border-radius: 12px;
  transition: background-color 0.3s ease; /* 仅颜色变化动画 */
}

/* 新增：板块头部（标题+切换按钮） */
.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 新增：切换按钮样式 */
.translate-switch-btn {
  border-radius: 20px !important;
  padding: 4px 16px !important;
  font-size: 14px !important;
}

/* 板块悬停时仅变色 */
.section:hover {
  background-color: #f0f0f0;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  border-bottom: 1px solid #eeeeee;
  color: #1890ff; /* 蓝色标题 */
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 18px;
  background-color: #1890ff;
  border-radius: 2px;
  margin-right: 8px;
}

.phrases-list, .examples-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 新增：隐藏文本样式（用于屏蔽语言） */
.hidden-text {
  position: relative;
  color: transparent !important;
  cursor: pointer;
}

.hidden-text::after {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  height: 18px;
  background-color: #e5e5e5;
  border-radius: 3px;
}

.hidden-text:hover::after {
  background-color: #d0d0d0;
}

/* 短语条目样式 - 添加浮动动画 */
.phrase-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  background-color: #ffffff;
  border-radius: 8px;
  border-left: 3px solid #1890ff; /* 蓝色左侧边 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  transition: transform 0.3s ease, box-shadow 0.3s ease; /* 条目添加浮动相关动画 */
}

/* 短语条目悬停时浮动效果 */
.phrase-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.1);
  background-color: #00b578;
}

.phrase-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.phrase-text {
  font-size: 18px;
  font-weight: 500;
  color: #1a1a1a; /* 深色短语 */
  flex-grow: 1;
}

.phrase-meaning {
  color: #666666; /* 灰色释义 */
  font-size: 14px;
  padding-left: 2px;
}

/* 修改：排除隐藏文本的hover颜色变化 */
.phrase-item:hover .phrase-text:not(.hidden-text),
.phrase-item:hover .phrase-meaning:not(.hidden-text) {
  color: #ffffff !important;
}

/* 例句条目样式 - 添加浮动动画 */
.example-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  margin-bottom: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  border-left: 3px solid #722ed1; /* 紫色左侧边 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  transition: transform 0.3s ease, box-shadow 0.3s ease; /* 条目添加浮动相关动画 */
}

/* 例句条目悬停时浮动效果 */
.example-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(114, 46, 209, 0.1);
  background-color: #00b578;
}

.example-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.example-text {
  font-weight: 500;
  color: #1a1a1a; /* 深色例句 */
  flex-grow: 1;
}

.example-meaning {
  color: #666666; /* 灰色翻译 */
  font-size: 14px;
  padding-left: 2px;
}

/* 修改：排除隐藏文本的hover颜色变化 */
.example-item:hover .example-text:not(.hidden-text),
.example-item:hover .example-meaning:not(.hidden-text) {
  color: #ffffff !important;
}

/* 发音按钮通用样式 */
.phrase-pronounce-btn, .example-pronounce-btn {
  background-color: #e6f7ff !important;
  color: #1890ff !important;
  border: 1px solid #91d5ff !important;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.phrase-pronounce-btn:hover, .example-pronounce-btn:hover {
  background-color: #bae7ff !important;
  transform: scale(1.05);
}

/* 复制按钮样式 */
.copy-btn {
  background-color: #ffffff !important;
  color: #ff6a00 !important;
  border: 1px solid #b65d2f !important;
  border-radius: 50% !important;
  width: 32px !important;
  height: 32px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  margin-left: 4px !important;
  transition: all 0.2s ease !important;
}

.copy-btn:hover {
  background-color: #e6f7e9 !important;
  transform: scale(1.05) !important;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .word-detail-container {
    padding: 16px;
  }

  .word-title {
    font-size: 26px;
  }

  .word-header {
    gap: 12px;
    margin-bottom: 16px;
  }

  .back-btn, .pronounce-btn {
    width: 36px;
    height: 36px;
  }

  .section {
    padding: 12px;
    margin-bottom: 24px;
  }

  /* 响应式调整切换按钮 */
  .translate-switch-btn {
    padding: 3px 12px !important;
    font-size: 13px !important;
  }

  .word-meaning {
    max-width: 100%;
    font-size: 15px;
  }

  .phrase-item, .example-item {
    padding: 10px;
  }

  .copy-btn {
    width: 28px !important;
    height: 28px !important;
  }
}

@media (max-width: 480px) {
  .word-title {
    font-size: 22px;
  }

  .phonetic-text, .word-meaning {
    font-size: 14px;
  }

  .phrase-meaning, .example-meaning {
    font-size: 13px;
  }

  /* 小屏优化切换按钮布局 */
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
